﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System.Text.Json;

namespace Attribute_Extension
{
    public static class Server_Extension
    {
        /// <summary>
        /// 扩展 SqlSugar 项目
        /// </summary>
        /// <param name="services"></param>
        public static void AddSqlSugarClient(this IServiceCollection services)
        {
            string filePath = "appsettings.json"; // 配置文件路径（硬编码）
            // 读取 JSON 配置文件的内容
            string jsonString = File.ReadAllText(filePath);
            var GetConfig = "";
            // 使用 JsonDocument 解析 JSON 字符串
            using (JsonDocument document = JsonDocument.Parse(jsonString))
            {
                // 获取根元素
                JsonElement root = document.RootElement;

                // 获取 ConnectionStrings 节点下的 UserInforer 节点的值作为连接字符串
                GetConfig = root.GetProperty("ConnectionStrings").GetProperty("MySqlInfor").GetString();
            }


            services.AddScoped<ISqlSugarClient>(s =>
            {
                //Scoped用SqlSugarClient 
                SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.MySql,
                    ConnectionString = GetConfig,
                    IsAutoCloseConnection = true,
                },
               db =>
               {
                   //每次上下文都会执行

                   //获取IOC对象不要求在一个上下文
                   //var log=s.GetService<Log>()

                   //获取IOC对象要求在一个上下文
                   //var appServive = s.GetService<IHttpContextAccessor>();
                   //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();

                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {

                   };
               });
                return sqlSugar;
            });
        }
    }
}
